package secondStage.part5.多线程.线程同步;

/**
 * @ClassName: [SellTicket4]
 * @Description:
 * @Author: [黄劲松]
 * @CreateDate: [2021-04-05]
 * @Version: [v1.0]
 */
public class SellTicket2 implements Runnable {
    private int tickets = 100;
    private Object obj = new Object();//同一把锁

    @Override
    public void run() {
        while (true) {
            //tickets = 100;
            //t1, t2, t3
            //假设t1抢到了CPU的执行权
            //假设t2抢到了CPU的执行权，但是代码被锁只能在此等待t1完成
            synchronized (obj) {//同步代码块
                //t1进来后，就会把这段代码给锁起来
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                        //t1休息100毫秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //窗口1正在出售第100张票
                    System.out.println(Thread.currentThread().getName() + "正在售票第" + tickets + "张票");
                    tickets--;
                }
            }//t1出来了，这段代码的锁就被释放了
        }
    }
}
